﻿using Microsoft.Extensions.Primitives;
using Serilog.Context;

namespace Bookify.Api.Middleware
{
    public sealed class RequestContextLoggingMiddleware(RequestDelegate next)
    {
        private const string CorrelationIdHeaderName = "X-Correlation-Id";

        public Task Invoke(HttpContext context)
        {
            using (LogContext.PushProperty("CorrelationId", GetCorrelationId(context)))
            {
                return next(context);
            }
        }

        private static string GetCorrelationId(HttpContext context)
        {
            context.Request.Headers.TryGetValue(
                CorrelationIdHeaderName, out StringValues correlationId);                                      

            return correlationId.FirstOrDefault() ?? context.TraceIdentifier;
        }
    }
}
